package com.ta.gulimall.coupon.config.rabbitmq.listener;

import com.rabbitmq.client.Channel;
import com.ta.gulimall.common.utils.RedisUtil;
import com.ta.gulimall.coupon.config.rabbitmq.MqQueueConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Set;

@Component
@RabbitListener(queues = MqQueueConstant.SECKILL_STORE_QUEUE)
@Slf4j
public class SeckillStoreQueueConsume {
    @Autowired
    RedisUtil redisUtil;

    @RabbitHandler(isDefault = true)
    public void consume(Message message, Channel channel) throws IOException {
        String body = new String(message.getBody());
        //监听指定前缀key
        Set<String> keys = redisUtil.keys(body + "*");

        keys.forEach(key -> {
            String count = redisUtil.get(key).toString();
            if (!count.equals("0")) {
                redisUtil.del(key);
                log.error("===秒杀skuId商品回填=={}", key.split(body)[1]);
            }
        });

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
